<template>
  <a-drawer
    :title="adminId ? '编辑' : '新增'"
    placement="right"
    :closable="true"
    width="800"
   :maskClosable='false'
    :keyboard='false'
    @close="visible = false"
    v-model:open="visible"
  >
    <div>
      <a-form
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        ref="formRef"
        :rules="rules"
        :model="formData"
        label-position="top"
      >
        <a-form-item
          label="用户名"
          required
          name="account"
        >
          <a-input
            :disabled="adminId ? true : false"
            v-model:value="formData.account"
          ></a-input>
        </a-form-item>
        <a-form-item
          label="手机号"
          required
          name="phone"
        >
          <a-input v-model:value="formData.phone"></a-input>
        </a-form-item>
        <a-form-item
          label="昵称"
          required
          name="admin_name"
        >
          <a-input v-model:value="formData.admin_name"></a-input>
        </a-form-item>
        <a-form-item
          label="头像"
          name="avatar"
        >
          <ImageUpload
            ref="uploadRef"
            :limit="1"
            :fileSize="1"
            v-model:modelValue="formData.avatar"
          ></ImageUpload>
        </a-form-item>
        <a-form-item
          label="邮箱"
          name="email"
        >
          <a-input v-model:value="formData.email"></a-input>
        </a-form-item>

        <a-form-item
          v-if="!adminId"
          label="密码"
          name="password"
          :rules="[{ required: true, validator: validatePass, trigger: 'blur' }]"
        >
          <a-input v-model:value="formData.password"></a-input>
        </a-form-item>

        <a-form-item
          v-if="!adminId"
          label="再次确认密码"
          name="password2"
          :rules="[{ required: true, validator: validatePass2, trigger: 'blur' }]"
        >
          <a-input v-model:value="formData.password2"></a-input>
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button @click="visible = false">取消</a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="handleSave"
            style="margin-left: 20px"
          >
            确认
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>
<script setup>
  import config from '@/config/index.js'

  import { adminList, adminDel, adminUpdate, adminAdd } from '@/api/index.js'
  import Collect from 'collect.js'
  import { message } from 'ant-design-vue'

  import { ref, reactive, onMounted, nextTick, toRefs, defineEmits, defineExpose } from 'vue'
  import { useRouter } from 'vue-router'
  const loading = ref(false)
  const validatePass = async (_rule, value) => {
    debugger
    if (!value) {
      return Promise.reject('请输入密码')
    } else {
      return Promise.resolve()
    }
  }
  const validatePass2 = async (_rule, value) => {
    if (!value) {
      return Promise.reject('请再次输入密码')
    } else if (value !== formData.value.password) {
      return Promise.reject('两次密码不一致')
    } else {
      return Promise.resolve()
    }
  }
  const validateEmail = async (_rule, value) => {
    if (value) {
      if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
        return Promise.reject('请输入正确的邮箱')
      } else {
      }
    } else {
      return Promise.resolve()
    }
  }

  const validatePhone = async (_rule, value) => {
    if (value === '') {
      return Promise.reject('请输入手机号')
    } else if (value) {
      if (!/^1[3456789]\d{9}$/.test(value)) {
        return Promise.reject('请输入正确的手机号')
      }
    } else {
      return Promise.resolve()
    }
  }
  const emits = defineEmits(['adminReload'])

  const formData = ref({
    account: null,
    phone: null,
    admin_name: null,
    avatar: null,
    email: null,
    password: null,
    password2: null
  })
  let defForm = ref()
  const formRef = ref()
  const adminId = ref(null)
  const rules = {
    account: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'change'
      }
    ],

    phone: [
      {
        required: false,
        validator: validatePhone,
        trigger: 'blur'
      }
    ],
    admin_name: [
      {
        required: true,
        message: '请输入昵称',
        trigger: 'change'
      }
    ],
    // password: [
    //   {
    //     required: !adminId,
    //     validator: validatePass,
    //     trigger: 'blur'
    //   }
    // ],
    // password2: [
    //   {
    //     required: !adminId,
    //     validator: validatePass2,
    //     trigger: 'blur'
    //   }
    // ],
    email: [
      {
        required: false,
        validator: validateEmail,
        trigger: 'blur'
      }
    ]
  }

  const visible = ref(false)

  const handleSave = () => {
    formRef.value.validate().then(() => {
      let params = JSON.parse(JSON.stringify(formData.value))
      let http = adminId.value ? adminUpdate : adminAdd

      if (adminId.value) {
        const collection = Collect(formData.value)

        const diff = collection.diffAssoc(defForm)

        params = diff.all()
        params.admin_id = adminId.value
        if (Object.values(params).length == 1) {
        message.error('暂未修改')
        return
      }
      } else {
        delete params.admin_id
      }
     
      loading.value = true
     
        http(params)
        .then((res) => {
          if (res.errorCode) {
            loading.value = false
            message.error(res.msg)
            return
          }
          if (res.code == 200) {
            message.success('操作成功！')
            emits('adminReload')
            visible.value = false
          }
        })
        .catch((err) => {
        
          message.error(err.msg)
        })
        .finally(() => {
      
          loading.value = false
        })
     
    
    })
  }
  const init = (row) => {
    visible.value = true
    nextTick(() => {
      formRef.value.resetFields()

      if (row) {
        let dataRow = JSON.parse(JSON.stringify(row))
        formData.value = dataRow
        defForm = JSON.parse(JSON.stringify(row))
        adminId.value = formData.value.admin_id
      } else {
        adminId.value = null
        formData.value = {
          account: null,
          phone: null,
          admin_name: null,
          avatar: null,
          email: null,
          password: null,
          password2: null
        }
      }
    })
  }

  defineExpose({
    init
  })
</script>

<style scoped></style>
